package net.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Dustin
 */
public class ClientHandler extends Thread implements Protocol {
    private int index;
    private boolean connected;
    private Server server;
    private Socket socket;
    private BufferedWriter outputWriter;
    private BufferedReader inputReader;
    private Pattern p = Pattern.compile(COMMAND_PATTERN);
    private Matcher m;

    public ClientHandler(Server aServer, int n, Socket aSocket) {
        server = aServer;
        index = n;
        socket = aSocket;
        try {
            outputWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            connected = true;
            start();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(connected) {
            try {
                String readLine = inputReader.readLine();
                if(readLine != null) {
                    command(readLine);
                }
            } catch (IOException ex) {
                disconnect();
            }
        }
    }

    public int getIndex() {
        return index;
    }

    public void sendMessage(String message) {
        try {
            outputWriter.write(message);
            outputWriter.newLine();
            outputWriter.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void disconnect() {
        try {
            connected = false;
            outputWriter.close();
            inputReader.close();
            socket.close();
            server.removeClient(this);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void command(String readLine) {
        int command = -1;
        String[] parameters = null;

        m = p.matcher(readLine);
        if(m.matches()) {
            m.reset();
            if(m.find()) {
                command = Integer.parseInt(m.group(1));
                parameters = m.group(3).split(SEPARATOR);
            } else {
                System.out.println("No Match in find");
            }
            switch(command) {
                
            }
        } else {
            System.out.println("No Match in matches");
        }
    }
}
